#!/usr/bin/python

"""GLTree openGL application implementation"""

import scopiavf.engine.glcontext as glcontext
import sys
import camera
import math
import time
import tree
import xmltree
#import scopiavf.data.filesystem as filesystem
from numpy import *
from scopiavf.engine.rendertree import *
from scopiavf.engine.tools import *
import style.default


ESCAPE = '\033'

class manager_t( glcontext.GlContext ):
    "GlTree application inheriting from GlContext"

    capture = False

    def __init__( self, w, h, root):
        """Init function

                w, h        Width and height of the viewport
                root        Root xml node to visualice
                xmlcss      A dictionary that keeps a css style for
                            every node in the xml tree"""
        glcontext.GlContext.__init__(self, w, h )
        self.style = style.default.Style( self )
        self.domroot = xmltree.readDom( self, self.style, root )
        self.camera = camera.Camera( self, self.style, self.domroot, (0, 0, 0), 3.0, 0.5 )
        self.root = RenderViewportNode( self, self.style, self.camera, 0, 0, 1, 1)
        self.domroot.show()
        self.camera.goDynamic()
        self.moving = False

    def shutdown( self ):
        "Free data"
        self.camera.free()
        self.root.free()
        del self.camera
        del self.root

    def display(self):
        "Display function"
        self.depthTest( True )
        self.root.render()

    def keyboard(self, key, x, y):
        if key == 'c' or key == 'C':
            pass #self.capture = not self.capture
        elif key == ESCAPE:
            print 'Stoping background works'
            self.shutdown()
            print 'Done'
            sys.exit()

    def mouse( self, buttons, down, x, y):
        glcontext.GlContext.mouse( self, buttons, down, x, y)
        if down and buttons[2]:
            # right click focus on the root
            self.domroot.focus()
        # wheel for zoom
        elif down and buttons[3]: self.camera.closer()
        elif down and buttons[4]: self.camera.farer()
    
    def centerView( self, center, radius ):
        self.camera.goTo( center, radius )

    def timer(self):
        elapsed = glcontext.GlContext.timer(self)
        self.camera.update( elapsed )
        self.forceDisplay()


